package org.example.testcase;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.*;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import io.qameta.allure.*;
import org.testng.ITestContext;
import org.testng.annotations.*;
import java.nio.file.Paths;

@Epic("登录")
@Feature("登录")
@Owner("用例作者：yxc")
public class loginTest {
    Playwright playwright;
    Browser browser;
    BrowserContext context;
    Page page;

    // Path to store and load session state
    private static final String STORAGE_STATE_PATH = "auth.json";

    @BeforeClass
    void launchBrowser() {
        playwright = Playwright.create();
        browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true).setSlowMo(50));
    }

    @AfterClass
    void closeBrowser() {
        playwright.close();
    }

    @BeforeMethod
    void createContextAndPage() {
        Browser.NewContextOptions options = new Browser.NewContextOptions();
        if (Paths.get(STORAGE_STATE_PATH).toFile().exists()) {
            options.setStorageStatePath(Paths.get(STORAGE_STATE_PATH));
        }
        context = browser.newContext(options);
        page = context.newPage();
    }

    @AfterMethod
    void closeContext() {
        context.close();
    }

    @BeforeMethod
    public void setUpTest(ITestContext context) {
        context.setAttribute("page", this.page);
    }


    @Test(priority = 1)
    @Description("登录成功并切换租户")
    public void loginSuccess() {
        page.navigate("http://192.168.7.136:3000/");

        //如果已经登录不登录
        if (Paths.get(STORAGE_STATE_PATH).toFile().exists()) {
            System.out.println("User already logged in, skipping login.");
        } else {
            page.getByPlaceholder("请输入账号").fill("028845");
            page.getByRole(AriaRole.TEXTBOX, new Page.GetByRoleOptions().setName("请输入密码")).fill("Julian1!");
            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("登录")).click();
            page.locator(".el-icon-caret-bottom").click();
            page.locator("xpath=//li[contains(., '巨联数字')]").click();
            context.storageState(new BrowserContext.StorageStateOptions().setPath(Paths.get(STORAGE_STATE_PATH)));



        }
    }

}
